package com.kate.mall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kate.mall.common.utils.R;
import com.kate.mall.gateway.config.IgnoreUrlsConfig;
import com.kate.mall.gateway.constant.AuthConstant;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.text.ParseException;

/**
 * 将登录用户的JWT转化成用户信息的全局过滤器
 * Created by kate2chan on 2020/6/17.
 */
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        ServerHttpRequest request = exchange.getRequest();
        if (StrUtil.isEmpty(token)) {
            return chain.filter(exchange);
        }
        /******************************************黑名单认证开始******************************************************/
        token = token.replace("Bearer", Strings.EMPTY);
        JWSObject jwsObject = null;
        try {
            jwsObject = JWSObject.parse(token);

            String payload = jwsObject.getPayload().toString();

            // 黑名单token(登出、修改密码)校验
            JSONObject jsonObject = JSONUtil.parseObj(payload);
            String jti = jsonObject.getStr("jti"); // JWT唯一标识

            Boolean isBlack = redisTemplate.hasKey(AuthConstant.TOKEN_BLACKLIST_PREFIX + jti);
            if (isBlack) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.OK);
                response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                response.getHeaders().set("Access-Control-Allow-Origin", "*");
                response.getHeaders().set("Cache-Control", "no-cache");

                String body = JSONUtil.toJsonStr(R.unauthorized("登录已退出，请重新登录！！"));
                DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(Charset.forName("UTF-8")));
                return response.writeWith(Mono.just(buffer));
            }
            /******************************************黑名单认证结束******************************************************/


            //从token中解析用户信息并设置到Header中去
            String realToken = token.replace("Bearer ", "");
            //jwsObject = JWSObject.parse(realToken);
            //String userStr = jwsObject.getPayload().toString();
            log.info("AuthGlobalFilter.filter() user:{}", payload);
            request = exchange.getRequest().mutate().header("user", payload).build();
            exchange = exchange.mutate().request(request).build();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
